/*
 * @Date: 2021-02-15 11:45:02
 * @LastEditors: 小枫
 * @description: 服务器启动脚本
 * @LastEditTime: 2021-02-15 14:08:25
 * @FilePath: \ssr\server\index.js
 */
const express = require('express')
const fs = require('fs')
// const Vue = require('vue')

const app = express()

const serverBundle = require('../dist/server/vue-ssr-server-bundle.json')
const clientManifest = require('../dist/client/vue-ssr-client-manifest.json')

// 创建渲染器
// createRenderer()是一个工厂函数，会染回一个渲染器
const { createBundleRenderer } = require('vue-server-renderer')
const renderer = createBundleRenderer(serverBundle, {
  runInNewContext: false,
  // 记得新建一个模板
  template: fs.readFileSync('../public/index.temp.html', 'utf-8'),
  clientManifest
})

app.use(express.static('../dist/client', {index: false}))

// const page = new Vue({
//   template: `<div>hello ssr</div>`
// })

// 设置路由
app.get('*', async (req, res) => {
  try {
    const context = {
      url: req.url,
      title: 'ssr test'
    }
    const html = await renderer.renderToString(context)
    res.send(html)
  } catch (error) {
    console.log(error);
    res.status(500).send('服务器错错误')
  }
})

app.listen(3000, () => {
  console.log('server listening port:3000');
})
